package com.ldu.houserent.common.schedule;

import com.ldu.houserent.common.enums.HouseStatusEnum;
import com.ldu.houserent.common.enums.OrderStatusEnum;
import com.ldu.houserent.entity.House;
import com.ldu.houserent.entity.Order;
import com.ldu.houserent.service.HouseService;
import com.ldu.houserent.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 每分钟定时扫描正在租赁中的房屋，如果到期了，则结束租赁状态，修改成待出租状态
 */
@Component      //自动执行，需要把该类声明为Component
public class TimerTask {

    @Autowired
    private OrderService orderService;
    @Autowired
    private HouseService houseService;

    /*
        每分钟执行一次
     */
    @Scheduled(cron = "0 */1 * * * ?")      //  s,min,hour,dayofMonth,month,dayofWeek*：表示匹配该域的任意值，假如在Minutes域使用*, 即表示每分钟都会触发事件。
    public void endOrderTimer(){
        List<Order> list = orderService.findOverDueOrderList();     //查询到期的订单
        if (list==null || list.size()==0){      //没有要到期的订单
            return;
        }
        for (Order order:list){
            //更新订单状态
            order.setStatus(OrderStatusEnum.FINISH.getValue());     //订单状态修改为已到期的状态，随后再次房屋的状态改成未租出状态
            orderService.update(order);
            //更新房屋状态
            House house = houseService.get(order.getHouseId());
            if (house!=null){
                house.setStatus(HouseStatusEnum.NOT_RENT.getValue());       //房屋状态改成未租出状态
                houseService.update(house);
            }

        }

    }
}
